package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.FGBiz;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.cmb01.util.DESUtils;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.StringUtils;
import com.fingard.dsp.bank.reqrespobj.contract.ReqContract;
import com.fingard.dsp.bank.reqrespobj.contract.ReqQryBatContract;
import com.fingard.dsp.bank.reqrespobj.contract.RetAtsContract;
import com.fingard.dsp.bank.reqrespobj.contract.RetAtsQryBatContract;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URLEncoder;

public class CMB01Contract extends CMB01Base implements IContract {
    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;

        try {
            String merchatId = getBankConfig().getMapValueByKey("contractInfoMapping", "merchatId");
            String mouldNo = getBankConfig().getMapValueByKey("contractInfoMapping", "mouldNo");
            String jumpUrl = StringUtils.isEmpty(p_req.contractDetail.jumpUrl) ? getBankConfig().getMapValueByKey("contractInfoMapping", "jumpUrl") : p_req.contractDetail.jumpUrl;
            String properUrl = getBankConfig().getMapValueByKey("contractInfoMapping", "properUrl");
            String desEncryptKey = getBankConfig().getMapValueByKey("contractInfoMapping", "desEncryptKey");

            StringBuilder signBuilder = new StringBuilder();
            signBuilder.append(merchatId);
            signBuilder.append(mouldNo);
            signBuilder.append(jumpUrl);
            signBuilder.append(properUrl);

            String waitSignStr = signBuilder.toString();
            WriteBankLogLn2("签名原始数据:\r\n" + waitSignStr);

            String md5Str = DigestHelper.cryptoMD5RetHexStr(waitSignStr.getBytes("UTF-8")).toUpperCase();
            WriteBankLogLn2("MD5值:" + md5Str);

            String desStr = DESUtils.encode(md5Str, desEncryptKey);
            WriteBankLogLn2("DES值:" + desStr);

            StringBuilder tmpReqStr = new StringBuilder();
            tmpReqStr.append(bankFront.getUrl("contract"));
            tmpReqStr.append("&MerchantNum=").append(merchatId);
            tmpReqStr.append("&TemplateNum=").append(mouldNo);
            String encodeJumpUrl = URLEncoder.encode(URLEncoder.encode(jumpUrl, "UTF-8"), "UTF-8");
            System.out.println("encodeJumpUrl:" + encodeJumpUrl);
            tmpReqStr.append("&JumpUrl=").append(encodeJumpUrl);
            String encodePropelUrl = URLEncoder.encode(URLEncoder.encode(properUrl, "UTF-8"), "UTF-8");
            System.out.println("encodePropelUrl:" + encodePropelUrl);
            tmpReqStr.append("&PropelUrl=").append(encodePropelUrl);
            tmpReqStr.append("&Signature=").append(desStr);

            WriteBankLogLn2("发送银行请求数据:\r\n" + tmpReqStr.toString());

            tmpRetDetail.respCode = "0";
            tmpRetDetail.respInfo = "签约申请成功";
            tmpRetDetail.unifiedCode = "SC003";
            tmpRetDetail.signConfirmType = "4";
            tmpRetDetail.signUrl = tmpReqStr.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        FileReader reader = null;
        BufferedReader br = null;
        try {
            String tmpFileName = FGBiz.DSPHOME_Parent + File.separator + "signnotify";
            File tmpFile = new File(tmpFileName + File.separator + p_reqQry.contractDetail.payAct + ".txt");
            if (!tmpFile.exists()) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未签约";
            } else {
                StringBuilder result = new StringBuilder();
                reader = new FileReader(tmpFile);
                br = new BufferedReader(reader);//构造一个BufferedReader类来读取文件
                String s = null;
                while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                    result.append(s);
                }
                WriteBankLogLn("签约结果内容：" + result);
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result.toString(), tmpSbMsg);
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signState = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/SignState");
                tmpRetDetail.authCode = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/AuthCode");
                tmpRetDetail.payAct = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/PayAct");
                tmpRetDetail.deadLine = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/DealLine");
                String singleLimit = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/SingleLimit");
                if (StringHelper.hasAnyChar(singleLimit)) {
                    tmpRetDetail.singleLimit = StringHelper.amountDivide100(singleLimit);
                }
                tmpRetDetail.unifiedCode = tmpBkReader.getFirstText("/ATSYH/TransResp/TransParam/DetailRecord/UnifiedCode");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (br != null) {
                br.close();
            }
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}